const tree = [{
  code: '0001',
  opened: true,
  children: [{
    code: '0002',
    opened: true,
    children: [{
      code: '0003',
      opened: true,
      children: [{
        code: '0004',
        opened: true,
        children: []
      }]
    }, {
      code: '0005',
      opened: false,
      children: [{
        code: '0006',
        opened: true
      }]
    }, {
      code: '0007',
      opened: true,
      children: []
    }]
  }]
}]

function recursion(arr, fn = () => true, childrenKey = 'children'){
  return arr.reduce((last, obj) => {
    let result = last;
    if(fn(obj)){
      result = last.concat(obj)
      let children = obj[childrenKey]
      if(children && children.length) {
        result = result.concat(recursion(children, fn, childrenKey))
      }      
    }
    return result
  }, [])
}

console.log(recursion(tree, o => o.opened).map(o=>o.code))
